/**
 * 向量存储内存 - IntelliMark适配版
 * 简化版本的向量记忆管理
 */

import { Document } from "@langchain/core/documents";
import { VectorStoreMemory as IVectorStoreMemory } from "../types/memory";

export class VectorStoreMemory implements IVectorStoreMemory {
  public type: 'vector' = 'vector';
  public namespace: string;
  public enabled: boolean;
  public documents: Document[];
  public vectorStore: any;
  public embeddingModel: string;
  public similarityThreshold: number;
  public maxDocuments: number;

  constructor(namespace: string = 'default', maxDocuments: number = 10000) {
    this.namespace = namespace;
    this.enabled = true;
    this.documents = [];
    this.vectorStore = null; // 简化实现
    this.embeddingModel = 'text-embedding-ada-002';
    this.similarityThreshold = 0.7;
    this.maxDocuments = maxDocuments;
  }

  async addDocument(document: Document): Promise<void> {
    this.documents.push(document);

    // 保持文档数量在限制内
    if (this.documents.length > this.maxDocuments) {
      this.documents = this.documents.slice(-this.maxDocuments);
    }
  }

  async addDocuments(documents: Document[]): Promise<void> {
    for (const doc of documents) {
      await this.addDocument(doc);
    }
  }

  async search(query: string, k: number = 10): Promise<Document[]> {
    // 简化实现：基于关键词匹配搜索
    const queryLower = query.toLowerCase();
    const scored = this.documents
      .map(doc => ({
        doc,
        score: this.calculateSimilarity(queryLower, doc.pageContent.toLowerCase())
      }))
      .filter(item => item.score >= this.similarityThreshold)
      .sort((a, b) => b.score - a.score)
      .slice(0, k)
      .map(item => item.doc);

    return scored;
  }

  async deleteDocument(documentId: string): Promise<void> {
    this.documents = this.documents.filter(doc => doc.metadata.id !== documentId);
  }

  async updateDocument(documentId: string, document: Document): Promise<void> {
    const index = this.documents.findIndex(doc => doc.metadata.id === documentId);
    if (index !== -1) {
      this.documents[index] = document;
    }
  }

  async clear(): Promise<void> {
    this.documents = [];
  }

  async save(): Promise<void> {
    // 简化实现：在内存中保存
  }

  async load(): Promise<void> {
    // 简化实现：从内存中加载
  }

  private calculateSimilarity(query: string, content: string): number {
    // 简化的相似度计算
    const queryWords = query.split(/\s+/);
    const contentWords = content.split(/\s+/);

    let matchCount = 0;
    for (const queryWord of queryWords) {
      if (contentWords.some(contentWord => contentWord.includes(queryWord) || queryWord.includes(contentWord))) {
        matchCount++;
      }
    }

    return matchCount / queryWords.length;
  }
}

export default VectorStoreMemory;